package com.mnemonic.storage.impl;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.List;

import com.mnemonic.storage.StorageAble;
import com.mnemonic.storage.StorageService;
import com.mnemonic.utils.IOUtils;
import com.mnemonic.utils.JavaSerializer;
import com.mnemonic.utils.OS;

/**
 * 基于文件的存储服务
 * 
 * @author lifeng
 * @date 2021/05/12
 */
public class AbstractStorageService<T extends StorageAble> implements StorageService<T> {

    /**
     * 实际的模型
     */
    private Class<?> model;

    /**
     * 获得文件夹的引用
     */
    private File dir;

    public AbstractStorageService() {

        // 获得泛型的实际类型
        this.model = this.extractModelClass4Class();

        // 文件的存储服务
        this.dir = new File(OS.home(), "." + model.getSimpleName());
        this.dir.mkdirs();
    }

    @Override
    public void save(T root) {
        File file = new File(dir, root.getId());
        // String xml = JaxbMapper.toXml(root, root.getClass());
        IOUtils.write(file, JavaSerializer.serialize(root));
    }

    @Override
    public List<T> list() {
        File[] csvs = dir.listFiles((dir, name) -> {
            return true;
        });
        List<T> objs = new ArrayList<>();
        for (File file : csvs) {
            T o = this.toObj(file);
            if (o != null) {
                objs.add(o);
            }
        }
        return objs;
    }

    @SuppressWarnings("unchecked")
    private T toObj(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return (T)JavaSerializer.deserialize(IOUtils.read(file));
            // return (T)JaxbMapper.fromXml(fis, model);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    /**
     * 提取泛型模型,多泛型的时候请将泛型T放在第一位
     */
    private Class<?> extractModelClass4Class() {
        Type type = this.getClass().getGenericSuperclass();
        ParameterizedType target = null;
        if (type instanceof ParameterizedType) {
            Type[] typeArray = ((ParameterizedType)type).getActualTypeArguments();
            if (typeArray != null && typeArray.length > 0) {
                for (Type t : typeArray) {
                    if (t instanceof TypeVariable || t instanceof WildcardType) {
                        break;
                    } else {
                        target = (ParameterizedType)type;
                        break;
                    }
                }
            }
        }
        return target == null ? null : (Class<?>)target.getActualTypeArguments()[0];
    }

    @Override
    public void clear() {
        File[] csvs = dir.listFiles((dir, name) -> {
            return true;
        });
        for (File file : csvs) {
            file.delete();
        }
    }
}
